iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0

自定義元件的插槽

多具名插槽的用法

  • 具名插槽是指為插槽設定一個具體的名稱,在使用元件時,可以透過插槽名稱來設定插槽的內容。
  • 由於具名插槽可以非常明確地指定插槽內容的位置,因此當一個元件要支援多個插槽時,通常需要使用具名插槽。
  • 例如要撰寫一個容器元件,此元件由標頭元素、主元素和尾部元素組成,此元件就需要有3個插槽,具名插槽的用法範例如下:
<div id="Application">
    <my-container2>
        <template v-slot:header>
        <h1>這裡是標頭元素</h1>
        </template>
        <template v-slot:main>
        <p>內容部分</p>
        <p>內容部分</p>
        </template>
        <template v-slot:footer>
        <p>這裡是尾部元素</p>
        </template>
    </my-container2>
</div>

<script>
    const App = Vue.createApp({
    })
    const container2Component = {
        template:'<div><slot name="header"></slot><hr/><slot name="main"></slot><hr/><slot name="footer"></slot></div>'
    }
    App.component("my-container2", container2Component)
    App.mount("#Application")
</script>
  • 如以上程式所示,在元件內部定義slot插槽時,可以使用name屬性來為其設定具體的名稱,需要注意的是,在使用此元件時,要使用template標籤來包裝插槽內容,對於template標籤,透過v-slot來指定與其對應的插槽位置。
  • 執行結果如下圖:
    https://ithelp.ithome.com.tw/upload/images/20251014/20169282HGT0467az5.png

上一篇
Day 28
下一篇
Day 30
系列文
從零開始學習TypeScript、Vue.js !!30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言